#import "wooddoc.h"

@implementation WoodDoc (Name)

static char 		*defaultFormat		= NULL;		// Default title format
static const char 	*extension			= NULL;		// Document extension

+ setDocExtension:(const char *)newExtension
{
    extension = newExtension;	
    return self;
}

+ (const char *)docExtension
{
	return extension;
}

+ setDefaultTitleFormat:(const char *)newDefault
{
	char temp[MAXPATHLEN+1];
	
    if (defaultFormat) 
		NX_FREE(defaultFormat);
	sprintf(temp,"%s.%s",newDefault,[self docExtension]);
    defaultFormat = NXCopyStringBufferFromZone(temp,[self zone]);
    return self;
}

+ (const char *)defaultTitleFormat
{
	return defaultFormat;
}

- (const char *)fileName
{
    static char filenameBuf[MAXPATHLEN+1];

    if (!directory && !name) 
		[self setName:NULL andDirectory:NULL];
    if (directory) {
		strcpy(filenameBuf, directory);
		strcat(filenameBuf, "/");
    } else 
		filenameBuf[0] = '\0';
    if (name) 
		strcat(filenameBuf, name);
    return filenameBuf;
}

- (const char *)directory
{
    return directory;
}

- (const char *)name
{
    return name;
}

- setName:(const char *)newName andDirectory:(const char *)newDirectory
{
    char newNameBuf[MAXPATHLEN+1];
    static int uniqueCount = 1;

    if ((newName && *newName) || !name) {
		if (!newName || !*newName) {
			sprintf(newNameBuf, [[self class] defaultTitleFormat], uniqueCount++);
			newName = newNameBuf;
		} else if (name) 
			NX_FREE(name);
		name = NXCopyStringBufferFromZone(newName, [self zone]);
    }
    if ((newDirectory && (*newDirectory == '/')) || !directory) {
		if (!newDirectory || (*newDirectory != '/')) 
			newDirectory = [NXApp currentDirectory];
		else if (directory) 
			NX_FREE(directory);
		directory = NXCopyStringBufferFromZone(newDirectory, [self zone]);
    }
	if(theOOEClient != nil || isOOEServer) {
	    [self setTitle_OOE:self];
	    return self;
    }
    [window setTitleAsFilename:[self fileName]];
    NXNameZone([self zone], [self fileName]);
    return self;
}

- setName:(const char *)file
{
    char *lastComponent;
    char path[MAXPATHLEN+1];

    if (file) {
		strcpy(path, file);
		lastComponent = rindex(path, '.');
		if(lastComponent && !strcmp(lastComponent + 1, "diagram2"))
			return self;
		lastComponent = rindex(path, '/');
		if (lastComponent) {
			*lastComponent++ = '\0';
			return [self setName:lastComponent andDirectory:path];
		} else 
			return [self setName:file andDirectory:NULL];
	}
    return self;
}

@end
